<template>
  <div>
    <h1>customRef</h1>
    <h1>{{ keyWordsRef }}</h1>
    <input type="text" v-model="keyWordsRef" />
    <h1>{{ keyWordsCustomRef }}</h1>
    <input type="text" v-model="keyWordsCustomRef" />
  </div>
</template>

<script lang="ts">
import { defineComponent, customRef, ref } from "vue";

export default defineComponent({
  setup() {
    const keyWordsRef = ref("");

    const keyWordsCustomRef = useCustomRef("");
    // 通过customRef自定义一个Ref
    function useCustomRef<T>(value: T, delay = 500) {
      return customRef((track, trigger) => {
        let timeout: number;
        return {
          get() {
            //  告诉vue追踪数据
            track();
            return value;
          },
          set(newValue: T) {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
              value = newValue;
              // 当value改变得到新值，trigger告诉vue更新界面
              trigger();
            }, delay);
          },
        };
      });
    }
    return {
      keyWordsRef,
      keyWordsCustomRef,
    };
  },
});
</script>

<style scoped>

</style>